// 玩家飞机爆炸特效类
import { TimeManager } from './TimeManager.js';

export class PlayerExplosion {
    constructor(x, y) {
        this.x = x;
        this.y = y;
        this.life = TimeManager.CONSTANTS.PLAYER_EXPLOSION_LIFE || 3000; // 3秒爆炸效果（比精英敌机更长）
        this.maxLife = this.life;
        this.completed = false; // 爆炸是否完成
        
        // 爆炸阶段
        this.phase = 0; // 0: 初始冲击, 1: 主爆炸, 2: 二次爆炸, 3: 余波
        this.phaseTimer = 0;
        
        // 主爆炸效果
        this.mainExplosionRadius = 0;
        this.maxMainRadius = 100; // 比精英敌机稍大
        
        // 二次爆炸效果
        this.secondaryExplosions = [];
        this.initSecondaryExplosions();
        
        // 冲击波效果
        this.shockwaveRadius = 0;
        this.maxShockwaveRadius = 150;
        
        // 碎片系统（更多碎片）
        this.debris = [];
        this.initDebris();
        
        // 火花系统（更密集）
        this.sparks = [];
        this.initSparks();
        
        // 能量环（更多层）
        this.energyRings = [];
        this.initEnergyRings();
        
        // 烟雾粒子（更持久）
        this.smokeParticles = [];
        this.initSmokeParticles();
        
        // 玩家特有的蓝色能量爆炸
        this.playerEnergyBurst = {
            radius: 0,
            maxRadius: 80,
            active: false
        };
    }
    
    initSecondaryExplosions() {
        // 创建多个次级爆炸点（模拟飞机各部分爆炸）
        const positions = [
            { x: -15, y: -10 }, // 左翼
            { x: 15, y: -10 },  // 右翼
            { x: 0, y: 10 },    // 引擎
            { x: -8, y: 0 },    // 左侧
            { x: 8, y: 0 }      // 右侧
        ];
        
        for (let i = 0; i < positions.length; i++) {
            this.secondaryExplosions.push({
                x: this.x + positions[i].x,
                y: this.y + positions[i].y,
                radius: 0,
                maxRadius: 40 + Math.random() * 20,
                delay: 200 + i * 150, // 延迟爆炸
                active: false,
                alpha: 0.8
            });
        }
    }
    
    initDebris() {
        // 创建更多机身碎片（18块）
        for (let i = 0; i < 18; i++) {
            const angle = (i / 18) * Math.PI * 2;
            const speed = Math.random() * 5 + 3;
            this.debris.push({
                x: this.x,
                y: this.y,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                rotation: Math.random() * Math.PI * 2,
                rotationSpeed: (Math.random() - 0.5) * 0.4,
                size: Math.random() * 10 + 6,
                color: ['#00ff41', '#66ff66', '#44cc44', '#009900'][Math.floor(Math.random() * 4)], // 玩家绿色主题
                life: this.maxLife * 0.9,
                maxLife: this.maxLife * 0.9
            });
        }
    }
    
    initSparks() {
        // 创建更多电火花效果（35个）
        for (let i = 0; i < 35; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 8 + 4;
            this.sparks.push({
                x: this.x,
                y: this.y,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed,
                life: Math.random() * 1000 + 600,
                maxLife: Math.random() * 1000 + 600,
                brightness: Math.random() * 0.6 + 0.4,
                color: ['#00ff88', '#ffffff', '#88ffaa', '#44ff66'][Math.floor(Math.random() * 4)] // 绿色主题火花
            });
        }
    }
    
    initEnergyRings() {
        // 创建更多能量冲击环（5个）
        for (let i = 0; i < 5; i++) {
            this.energyRings.push({
                radius: 0,
                maxRadius: 70 + i * 25,
                speed: 1.0 + i * 0.4,
                alpha: 0.9 - i * 0.15,
                delay: i * 120, // 延迟出现
                active: false,
                color: i % 2 === 0 ? [0, 255, 136] : [68, 255, 102] // 交替绿色
            });
        }
    }
    
    initSmokeParticles() {
        // 创建更多烟雾粒子（25个）
        for (let i = 0; i < 25; i++) {
            const angle = Math.random() * Math.PI * 2;
            const speed = Math.random() * 2.5 + 1;
            this.smokeParticles.push({
                x: this.x + (Math.random() - 0.5) * 50,
                y: this.y + (Math.random() - 0.5) * 50,
                vx: Math.cos(angle) * speed,
                vy: Math.sin(angle) * speed - 1.5, // 向上飘得更快
                size: Math.random() * 25 + 15,
                maxSize: Math.random() * 50 + 40,
                alpha: 0.7,
                life: this.maxLife,
                maxLife: this.maxLife
            });
        }
    }
    
    update(deltaTime) {
        this.life = TimeManager.updateTimer(this.life, deltaTime);
        this.phaseTimer += deltaTime;
        
        // 更新爆炸阶段
        if (this.phaseTimer < 400) {
            this.phase = 0; // 初始冲击
        } else if (this.phaseTimer < 1200) {
            this.phase = 1; // 主爆炸
        } else if (this.phaseTimer < 2000) {
            this.phase = 2; // 二次爆炸
        } else {
            this.phase = 3; // 余波
        }
        
        // 更新主爆炸半径
        if (this.phase <= 1) {
            this.mainExplosionRadius = Math.min(
                this.maxMainRadius, 
                (this.phaseTimer / 1200) * this.maxMainRadius
            );
        }
        
        // 更新冲击波
        if (this.phase === 0) {
            this.shockwaveRadius = Math.min(
                this.maxShockwaveRadius,
                (this.phaseTimer / 400) * this.maxShockwaveRadius
            );
        }
        
        // 更新玩家能量爆发
        if (this.phaseTimer > 100 && this.phaseTimer < 800) {
            this.playerEnergyBurst.active = true;
            this.playerEnergyBurst.radius = Math.min(
                this.playerEnergyBurst.maxRadius,
                ((this.phaseTimer - 100) / 700) * this.playerEnergyBurst.maxRadius
            );
        }
        
        // 更新次级爆炸
        for (let explosion of this.secondaryExplosions) {
            if (this.phaseTimer > explosion.delay && !explosion.active) {
                explosion.active = true;
            }
            if (explosion.active) {
                explosion.radius += 2.5 * (deltaTime / 16.67);
                explosion.alpha *= Math.pow(0.98, deltaTime / 16.67);
            }
        }
        
        // 更新碎片
        for (let debris of this.debris) {
            debris.x += debris.vx * (deltaTime / 16.67);
            debris.y += debris.vy * (deltaTime / 16.67);
            debris.vy += 0.12 * (deltaTime / 16.67); // 重力
            debris.rotation += debris.rotationSpeed * (deltaTime / 16.67);
            debris.life = TimeManager.updateTimer(debris.life, deltaTime);
        }
        
        // 更新火花
        for (let spark of this.sparks) {
            spark.x += spark.vx * (deltaTime / 16.67);
            spark.y += spark.vy * (deltaTime / 16.67);
            spark.vx *= Math.pow(0.93, deltaTime / 16.67); // 阻力
            spark.vy *= Math.pow(0.93, deltaTime / 16.67);
            spark.life = TimeManager.updateTimer(spark.life, deltaTime);
        }
        
        // 更新能量环
        for (let ring of this.energyRings) {
            if (this.phaseTimer > ring.delay) {
                ring.active = true;
                ring.radius += ring.speed * (deltaTime / 16.67);
            }
        }
        
        // 更新烟雾粒子
        for (let smoke of this.smokeParticles) {
            smoke.x += smoke.vx * (deltaTime / 16.67);
            smoke.y += smoke.vy * (deltaTime / 16.67);
            smoke.size += (smoke.maxSize - smoke.size) * 0.015 * (deltaTime / 16.67);
            smoke.alpha *= Math.pow(0.985, deltaTime / 16.67);
            smoke.life = TimeManager.updateTimer(smoke.life, deltaTime);
        }
        
        // 检查爆炸是否完成
        if (TimeManager.isTimeUp(this.life)) {
            this.completed = true;
        }
        
        return !this.completed;
    }
    
    render(ctx) {
        ctx.save();
        
        // 渲染冲击波
        if (this.phase === 0 && this.shockwaveRadius > 0) {
            this.renderShockwave(ctx);
        }
        
        // 渲染烟雾粒子（在背景）
        this.renderSmokeParticles(ctx);
        
        // 渲染次级爆炸
        this.renderSecondaryExplosions(ctx);
        
        // 渲染主爆炸
        if (this.phase <= 1) {
            this.renderMainExplosion(ctx);
        }
        
        // 渲染玩家能量爆发
        if (this.playerEnergyBurst.active) {
            this.renderPlayerEnergyBurst(ctx);
        }
        
        // 渲染能量环
        this.renderEnergyRings(ctx);
        
        // 渲染碎片
        this.renderDebris(ctx);
        
        // 渲染火花
        this.renderSparks(ctx);
        
        // 渲染闪光效果
        if (this.phase === 0) {
            this.renderFlash(ctx);
        }
        
        ctx.restore();
    }
    
    renderShockwave(ctx) {
        // 强力冲击波环
        for (let i = 0; i < 4; i++) {
            const radius = Math.max(0, this.shockwaveRadius - i * 20);
            if (radius > 0) {
                const alpha = (1 - this.shockwaveRadius / this.maxShockwaveRadius) * (1 - i * 0.25);
                
                ctx.strokeStyle = `rgba(0, 255, 136, ${alpha})`;
                ctx.lineWidth = 5 - i;
                ctx.beginPath();
                ctx.arc(this.x, this.y, radius, 0, Math.PI * 2);
                ctx.stroke();
            }
        }
    }
    
    renderMainExplosion(ctx) {
        // 主爆炸火球（绿色主题）
        const progress = this.mainExplosionRadius / this.maxMainRadius;
        const alpha = 1 - progress * 0.6;
        const safeRadius = Math.max(0, this.mainExplosionRadius);
        
        if (safeRadius <= 0) return;
        
        // 外层火焰
        const outerGradient = ctx.createRadialGradient(
            this.x, this.y, 0,
            this.x, this.y, safeRadius
        );
        outerGradient.addColorStop(0, `rgba(255, 255, 255, ${alpha})`);
        outerGradient.addColorStop(0.2, `rgba(200, 255, 200, ${alpha * 0.9})`);
        outerGradient.addColorStop(0.5, `rgba(0, 255, 136, ${alpha * 0.7})`);
        outerGradient.addColorStop(0.8, `rgba(0, 200, 100, ${alpha * 0.5})`);
        outerGradient.addColorStop(1, 'rgba(0, 150, 75, 0)');
        
        ctx.fillStyle = outerGradient;
        ctx.beginPath();
        ctx.arc(this.x, this.y, safeRadius, 0, Math.PI * 2);
        ctx.fill();
        
        // 内层核心
        const coreRadius = Math.max(0, safeRadius * 0.5);
        if (coreRadius > 0) {
            const coreGradient = ctx.createRadialGradient(
                this.x, this.y, 0,
                this.x, this.y, coreRadius
            );
            coreGradient.addColorStop(0, `rgba(255, 255, 255, ${alpha})`);
            coreGradient.addColorStop(0.4, `rgba(255, 255, 200, ${alpha * 0.8})`);
            coreGradient.addColorStop(1, `rgba(200, 255, 200, ${alpha * 0.4})`);
            
            ctx.fillStyle = coreGradient;
            ctx.beginPath();
            ctx.arc(this.x, this.y, coreRadius, 0, Math.PI * 2);
            ctx.fill();
        }
    }
    
    renderPlayerEnergyBurst(ctx) {
        // 玩家特有的蓝绿色能量爆发
        const safeRadius = Math.max(0, this.playerEnergyBurst.radius);
        if (safeRadius <= 0) return;
        
        const alpha = 0.6 * (1 - this.playerEnergyBurst.radius / this.playerEnergyBurst.maxRadius);
        
        const gradient = ctx.createRadialGradient(
            this.x, this.y, safeRadius * 0.3,
            this.x, this.y, safeRadius
        );
        gradient.addColorStop(0, `rgba(68, 255, 255, ${alpha})`);
        gradient.addColorStop(0.6, `rgba(0, 255, 136, ${alpha * 0.7})`);
        gradient.addColorStop(1, `rgba(0, 200, 100, 0)`);
        
        ctx.fillStyle = gradient;
        ctx.beginPath();
        ctx.arc(this.x, this.y, safeRadius, 0, Math.PI * 2);
        ctx.fill();
    }
    
    renderSecondaryExplosions(ctx) {
        for (let explosion of this.secondaryExplosions) {
            if (explosion.active && explosion.alpha > 0.01) {
                const safeRadius = Math.max(0, explosion.radius);
                if (safeRadius <= 0) continue;
                
                const gradient = ctx.createRadialGradient(
                    explosion.x, explosion.y, 0,
                    explosion.x, explosion.y, safeRadius
                );
                gradient.addColorStop(0, `rgba(255, 255, 255, ${explosion.alpha})`);
                gradient.addColorStop(0.4, `rgba(255, 200, 100, ${explosion.alpha * 0.8})`);
                gradient.addColorStop(0.8, `rgba(255, 100, 100, ${explosion.alpha * 0.6})`);
                gradient.addColorStop(1, 'rgba(200, 50, 50, 0)');
                
                ctx.fillStyle = gradient;
                ctx.beginPath();
                ctx.arc(explosion.x, explosion.y, safeRadius, 0, Math.PI * 2);
                ctx.fill();
            }
        }
    }
    
    renderEnergyRings(ctx) {
        for (let ring of this.energyRings) {
            if (ring.active && ring.radius < ring.maxRadius && ring.radius > 0) {
                const alpha = ring.alpha * (1 - ring.radius / ring.maxRadius);
                const safeRadius = Math.max(0, ring.radius);
                const safeInnerRadius = Math.max(0, ring.radius - 3);
                
                ctx.strokeStyle = `rgba(${ring.color[0]}, ${ring.color[1]}, ${ring.color[2]}, ${alpha})`;
                ctx.lineWidth = 4;
                ctx.beginPath();
                ctx.arc(this.x, this.y, safeRadius, 0, Math.PI * 2);
                ctx.stroke();
                
                // 内部发光
                if (safeInnerRadius > 0) {
                    ctx.strokeStyle = `rgba(${ring.color[0] + 50}, ${ring.color[1]}, ${ring.color[2] + 50}, ${alpha * 0.6})`;
                    ctx.lineWidth = 2;
                    ctx.beginPath();
                    ctx.arc(this.x, this.y, safeInnerRadius, 0, Math.PI * 2);
                    ctx.stroke();
                }
            }
        }
    }
    
    renderDebris(ctx) {
        for (let debris of this.debris) {
            if (!TimeManager.isTimeUp(debris.life)) {
                const alpha = debris.life / debris.maxLife;
                
                ctx.save();
                ctx.translate(debris.x, debris.y);
                ctx.rotate(debris.rotation);
                
                ctx.fillStyle = debris.color + Math.floor(alpha * 255).toString(16).padStart(2, '0');
                ctx.fillRect(-debris.size/2, -debris.size/2, debris.size, debris.size);
                
                // 发光边缘
                ctx.strokeStyle = `rgba(0, 255, 136, ${alpha * 0.6})`;
                ctx.lineWidth = 1;
                ctx.strokeRect(-debris.size/2, -debris.size/2, debris.size, debris.size);
                
                ctx.restore();
            }
        }
    }
    
    renderSparks(ctx) {
        for (let spark of this.sparks) {
            if (!TimeManager.isTimeUp(spark.life)) {
                const alpha = spark.life / spark.maxLife * spark.brightness;
                
                ctx.fillStyle = spark.color + Math.floor(alpha * 255).toString(16).padStart(2, '0');
                ctx.fillRect(spark.x - 1.5, spark.y - 1.5, 3, 3);
                
                // 拖尾效果
                ctx.strokeStyle = spark.color + Math.floor(alpha * 128).toString(16).padStart(2, '0');
                ctx.lineWidth = 1;
                ctx.beginPath();
                ctx.moveTo(spark.x, spark.y);
                ctx.lineTo(spark.x - spark.vx * 0.7, spark.y - spark.vy * 0.7);
                ctx.stroke();
            }
        }
    }
    
    renderSmokeParticles(ctx) {
        for (let smoke of this.smokeParticles) {
            if (!TimeManager.isTimeUp(smoke.life) && smoke.alpha > 0.01) {
                const safeSize = Math.max(0, smoke.size);
                
                if (safeSize > 0) {
                    const gradient = ctx.createRadialGradient(
                        smoke.x, smoke.y, 0,
                        smoke.x, smoke.y, safeSize
                    );
                    gradient.addColorStop(0, `rgba(80, 80, 80, ${smoke.alpha})`);
                    gradient.addColorStop(0.7, `rgba(60, 60, 60, ${smoke.alpha * 0.6})`);
                    gradient.addColorStop(1, 'rgba(40, 40, 40, 0)');
                    
                    ctx.fillStyle = gradient;
                    ctx.beginPath();
                    ctx.arc(smoke.x, smoke.y, safeSize, 0, Math.PI * 2);
                    ctx.fill();
                }
            }
        }
    }
    
    renderFlash(ctx) {
        // 强烈的白光闪烁（更持久）
        if (this.phaseTimer < 200) {
            const alpha = 0.9 * (1 - this.phaseTimer / 200);
            const flashRadius = Math.max(0, this.maxMainRadius * 2);
            
            if (flashRadius > 0) {
                ctx.fillStyle = `rgba(255, 255, 255, ${alpha})`;
                ctx.beginPath();
                ctx.arc(this.x, this.y, flashRadius, 0, Math.PI * 2);
                ctx.fill();
            }
        }
    }
}